//
//  CCGeRenZhongXinController.m
//  cc
//
//  Created by ZLQ on 2016/10/25.
//  Copyright © 2016年 hbyj. All rights reserved.
//

#import "CCGeRenZhongXinController.h"
#import "AFNetworking.h"
#import "NSString+Password.h"
#import "Util.h"
#import "CCGeRenZhuYeViewController.h"
#import "KFBox.h"
#import "CCKSZCViewController.h"
#import "CCForgetPassWordViewController.h"
#import "TwoViewController.h"
#import "CCLockViewController.h"
#import "MainViewController.h"
@interface CCGeRenZhongXinController ()
{
    UIImageView *_View;
    UIView *_bgView;
    UITextField *_pwd;
    UITextField *user;
}
@property(copy,nonatomic) NSString * accountNumber;
@property(copy,nonatomic) NSString * mmmm;
@property(copy,nonatomic) NSString * users;
@end

@implementation CCGeRenZhongXinController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=YES;
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    self.navigationController.navigationBarHidden=NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor=[UIColor whiteColor];
    
    _View=[[UIImageView alloc]initWithFrame:self.view.bounds];
    _View.image=[UIImage imageNamed:@"background"];
    [self.view addSubview:_View];
    
    //为了显示背景图片自定义navgationbar上面的三个按钮
    UIButton *but =[[UIButton alloc]initWithFrame:CGRectMake(5, 27, 35, 35)];
    [but setImage:[UIImage imageNamed:@"v2_goback"] forState:UIControlStateNormal];
    [but addTarget:self action:@selector(clickaddBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:but];
    
    UIButton *zhuce =[[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-60, 30, 50, 30)];
    [zhuce setTitle:@"注册" forState:UIControlStateNormal];
    [zhuce setTitleColor:[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1] forState:UIControlStateNormal];
    zhuce.titleLabel.font=[UIFont systemFontOfSize:17];
    // zhuce.font=[UIFont systemFontOfSize:17];
    [zhuce addTarget:self action:@selector(zhuce) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:zhuce];
    
    UILabel *lanel=[[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width-30)/2, 30, 50, 30)];
    lanel.text=@"登录";
    lanel.textColor=[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1];
    [self.view addSubview:lanel];
    
    [self createTextFields];
    [self createButtons];
}

/**
 *  实现返回按钮功能
 *
 *  点击返回首页
 */
-(void)clickaddBtn:(UIButton *)sender
{
    //[self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

/**
 *  添加文本框
 */
-(void)createTextFields
{
    CGRect frame=[UIScreen mainScreen].bounds;
    _bgView=[[UIView alloc]initWithFrame:CGRectMake(10, 75, frame.size.width-20, 100)];
    _bgView.layer.cornerRadius=3.0;
    _bgView.alpha=0.7;
    _bgView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:_bgView];
    
    user=[self createTextFielfFrame:CGRectMake(60, 10, 271, 30) font:[UIFont systemFontOfSize:14] placeholder:@"请输入您手机号码"];
    //user.text=@"13419693608";
    [user becomeFirstResponder];
    user.keyboardType=UIKeyboardTypeNumberPad;
    user.clearButtonMode = UITextFieldViewModeWhileEditing;
    [user addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    _pwd=[self createTextFielfFrame:CGRectMake(60, 60, 271, 30) font:[UIFont systemFontOfSize:14]  placeholder:@"密码" ];
    _pwd.clearButtonMode = UITextFieldViewModeWhileEditing;
    //pwd.text=@"123456";
    //密文样式
    _pwd.secureTextEntry=YES;
    //pwd.keyboardType=UIKeyboardTypeNumberPad;
    
    
    UIImageView *userImageView=[self createImageViewFrame:CGRectMake(20, 10, 25, 25) imageName:@"ic_landing_nickname" color:nil];
    UIImageView *pwdImageView=[self createImageViewFrame:CGRectMake(20, 60, 25, 25) imageName:@"mm_normal" color:nil];
    UIImageView *line1=[self createImageViewFrame:CGRectMake(20, 50, _bgView.frame.size.width-40, 1) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    [_bgView addSubview:user];
    [_bgView addSubview:_pwd];
    
    [_bgView addSubview:userImageView];
    [_bgView addSubview:pwdImageView];
    [_bgView addSubview:line1];
}

/**
 *  控制textfild的输入长度
 */
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField.text.length > 11) {
        textField.text = [textField.text substringToIndex:11];
    }
}

/**
 *  实现注册按钮功能
 */
-(void)zhuce
{
//    [self.navigationController pushViewController:[[CCKSZCViewController alloc]init] animated:YES];
    [self presentViewController:[[CCKSZCViewController alloc]init] animated:YES completion:nil];
}

/**
 *
 *
 *  @param frame       文本框frame
 *  @param font        文字大小
 *  @param placeholder 占位字符
 *  边框样式、背景颜色
 *
 */

-(UITextField *)createTextFielfFrame:(CGRect)frame font:(UIFont *)font placeholder:(NSString *)placeholder
{
    UITextField *textField=[[UITextField alloc]initWithFrame:frame];
    
    textField.font=font;
    
    textField.textColor=[UIColor grayColor];
    
    textField.borderStyle=UITextBorderStyleNone;
    
    textField.placeholder=placeholder;
    
    return textField;
}

/**
 *  判断是否有背景图片
 *
 *  有的话就使用背景图
 *  没有就设置背景颜色
 *  param color
 *
 *  return
 */
-(UIImageView *)createImageViewFrame:(CGRect)frame imageName:(NSString *)imageName color:(UIColor *)color
{
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:frame];
    
    if (imageName)
    {
        imageView.image=[UIImage imageNamed:imageName];
    }
    if (color)
    {
        imageView.backgroundColor=color;
    }
    
    return imageView;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [user resignFirstResponder];
    [_pwd resignFirstResponder];
}
-(void)createButtons
{
    UIButton *landBtn=[self createButtonFrame:CGRectMake(10, 190, self.view.frame.size.width-20, 37) backImageName:nil title:@"登录" titleColor:[UIColor whiteColor]  font:[UIFont systemFontOfSize:19] target:self action:@selector(landClick)];
    landBtn.backgroundColor=[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1];
    landBtn.layer.cornerRadius=5.0f;
    
    UIButton *newUserBtn=[self createButtonFrame:CGRectMake(5, 235, 70, 30) backImageName:nil title:@"快速注册" titleColor:[UIColor grayColor] font:[UIFont systemFontOfSize:13] target:self action:@selector(registration:)];
    //newUserBtn.backgroundColor=[UIColor lightGrayColor];
    
    UIButton *forgotPwdBtn=[self createButtonFrame:CGRectMake(self.view.frame.size.width-75, 235, 60, 30) backImageName:nil title:@"找回密码" titleColor:[UIColor grayColor] font:[UIFont systemFontOfSize:13] target:self action:@selector(fogetPwd:)];
    //fogotPwdBtn.backgroundColor=[UIColor lightGrayColor];
    
    
#define Start_X 60.0f           // 第一个按钮的X坐标
#define Start_Y 440.0f           // 第一个按钮的Y坐标
#define Width_Space 50.0f        // 2个按钮之间的横间距
#define Height_Space 20.0f      // 竖间距
#define Button_Height 50.0f    // 高
#define Button_Width 50.0f      // 宽
    
    [self.view addSubview:landBtn];
    [self.view addSubview:newUserBtn];
    [self.view addSubview:forgotPwdBtn];
}

/**
 *
 *
 *
 */
-(UIButton *)createButtonFrame:(CGRect)frame backImageName:(NSString *)imageName title:(NSString *)title titleColor:(UIColor *)color font:(UIFont *)font target:(id)target action:(SEL)action
{
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=frame;
    if (imageName)
    {
        [btn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    
    if (font)
    {
        btn.titleLabel.font=font;
    }
    
    if (title)
    {
        [btn setTitle:title forState:UIControlStateNormal];
    }
    if (color)
    {
        [btn setTitleColor:color forState:UIControlStateNormal];
    }
    if (target&&action)
    {
        [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }
    return btn;
}

-(void)touchesEnded:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
{
    [user resignFirstResponder];
    [_pwd resignFirstResponder];
}

/**
 *  点击登录按钮
 */
-(void)landClick
{
    //判断是不是 手机号
    BOOL a = [KFBox isMobileNumber:user.text];
    if (!a) {
        [SVProgressHUD showInfoWithStatus:@"请输入格式正确的手机号码"];
        return;
    }
    
    if ([user.text isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:@"请输入手机号码"];
        return;
    }
    else if (user.text.length < 11 || user.text.length >= 12)
    {
        [SVProgressHUD showInfoWithStatus:@"您输入的手机号码格式不正确"];
        // 延迟2秒后消失
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            
        });
        return;
    }
    else if ([_pwd.text isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:
         @"亲,请输入密码"];
        return;
    }
    else if (_pwd.text.length <6)
    {
        [SVProgressHUD showInfoWithStatus:
         @"亲,密码长度至少6位"];
        return;
        
    }else if (_pwd.text.length>20){
        [SVProgressHUD showInfoWithStatus:
         @"亲,密码长度不能超过20位"];
        
    }else{
        
        NSString *pwd = [_pwd.text myMD5];
        NSDictionary *parmar = @{@"username":user.text,@"pwd":pwd};
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:@"http://text.dawenkeji.com/Validate.asmx/Login" parameters:parmar progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *dict) {
            NSLog(@"=======%@",dict[@"userid"]);
            
            NSLog(@"上传成功");
            
            //如果返回值为‘0’表示匹配成功，可以登录
            if ([dict[@"messages"] isEqualToString:@"0"]) {
                
                //存储登录用户到单例
                UserEntity *userID = [Util getCurrentUserInfo];
                userID.isLogin = YES;
                userID.userName = user.text;
                
                //登录成功跳转到 "个人信息页面"
                [self.navigationController pushViewController:[[CCGeRenZhuYeViewController alloc]init] animated:YES];
                
            }else
            {
                [SVProgressHUD showInfoWithStatus:@"账号或密码有误，请查证后重新输入"];
                return ;
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"上传失败---->%@",error);
        }];
        
        /*++++++++++++++++++++++++++++因为没有实际后台支持 顾做假登录++++++++++++++++++++++++++++++++++*/
        //存储登录用户到单例
        UserEntity *userID = [Util getCurrentUserInfo];
        userID.isLogin = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"getInfo" object:nil userInfo:@{@"name":@"ZLQ",@"phone":user.text}];
        
        //登录成功跳转到‘个人信息页面’
        
        //判断是否是 由解锁页面进来的
        if ([self.shifoujiesouyemiandenglu isEqualToString:@"YES"]) {
            MainViewController *main = [[MainViewController alloc] init];
            [UIApplication sharedApplication].keyWindow.rootViewController = main;
            main.selectedIndex = 1;
            [user resignFirstResponder];
            [_pwd resignFirstResponder];
        }else{
            //登录界面是present进来的 所以返回上个界面就得dissmiss 方法
            //[self.navigationController popViewControllerAnimated:YES];
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        
        /*++++++++++++++++++++++++++++因为没有实际后台支持 顾做假登录++++++++++++++++++++++++++++++++++*/
    }
}

/**
 *  点击快速注册
 */
-(void)registration:(UIButton *)buton
{
    //[self.navigationController pushViewController:[[CCKSZCViewController alloc]init] animated:YES];
    [self presentViewController:[[CCKSZCViewController alloc]init] animated:YES completion:nil];
}
/**
 *  点击找回密码
 */
-(void)fogetPwd:(UIButton *)button
{
    //[self.navigationController pushViewController:[[CCForgetPassWordViewController alloc]init] animated:YES];
    [self presentViewController:[[CCForgetPassWordViewController alloc]init] animated:YES completion:nil];
}


@end
